package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 线程任务
 * 负责与特定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //1解析请求
        try {
            String line = readLine();
            System.out.println("请求行:"+line);

            String method;
            String uri;
            String protocol;

            String[] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);
            Map<String,String> headers = new HashMap<>();
            //解析消息头
            while (true){
                line = readLine();
                if (line.isEmpty()) {
                    break;
                }
                String[]arr=line.split(":\\s");
                headers.put(arr[0],arr[1]);
                System.out.println("消息头:"+line);
            }
            System.out.println(headers);





            //2处理请求
            //3发送响应
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    public String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';
        char pre = 'a';
        int d;
        while ((d = in.read()) != -1) {
            cur = (char) d;

            if (pre == 13 && cur == 10) {
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }
}


























